package cn.qayy.intercepter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.qayy.constants.Constant;
import cn.qayy.po.User;
import cn.qayy.utils.JsonResult;
/***
 * 权限拦截
 * 
 * @author jobs1127
 *
 */
public class PermissionInterceptor implements HandlerInterceptor {
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		//判断当前访问路径是否为登录的路径,如果是则放行
		//System.out.println("uri="+request.getRequestURI());
		String uri = request.getRequestURI(); 
		if(uri.indexOf("selectUserNameAndPassword.do") > 0 
				|| uri.indexOf("toLogin.do") > 0){
			return true;
		}
		//获取请求头，判断用户的请求类型，是传统同步请求，还是ajax异步请求
		String header = request.getHeader("x-requested-with");
		
		//判断session中是否有登录信息,如果没有则跳转到登录页面,如果有则放行
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		Boolean isLoginIndex = (Boolean)session.getAttribute("isLoginIndex");
		if(user != null){
			/**用户已登录，权限判断,目前的处理方式,权限为age=0的为只读权限**/
			if(user.getAge()==0) {
				ResourceBundle rb = ResourceBundle.getBundle("excludeUrl");
				Enumeration<String> keys = rb.getKeys();
				while(keys.hasMoreElements()) {
					if(uri.contains(keys.nextElement())) {
						if(header == null) {//传统同步请求
							response.sendRedirect(request.getContextPath()+"/405.jsp");
						} else {//ajax异步请求
							writeSecurityFilter(request,response,Constant.WITHOUT_PERMISSION_CODE);
						}
						return false;
					}
				}
			}
			/****
			 * 权限为age<=1的不具备财务权限，不能将操作毕相关的流向：毕->押，待；或者 押，待->毕 均不能操作
			 * 财务权限为2
			 */
			if(user.getAge()<=1) {
				if(uri.contains("caiwu")) {
					if(header == null) {//传统同步请求
						response.sendRedirect(request.getContextPath()+"/login.jsp");
					} else {//ajax异步请求
						writeSecurityFilter(request,response,Constant.WITHOUT_PERMISSION_CODE);
					}
					return false;
				}
			}
			/***
			 * 细粒度权限控制，跳转用户关心的页面,一次性的操作，跳转成功后，下次失效，需要下次登录后才生效
			 */
			if(user.getHobby()!=null && user.getHobby().contains(Constant.P_PLAN)) {
				if(isLoginIndex) {
					session.setAttribute("isLoginIndex",false);
					response.sendRedirect(request.getContextPath()+"/plan/ui.do");
				}
			}
			if(user.getHobby()!=null && user.getHobby().contains(Constant.P_CAIWU)) {
				if(isLoginIndex) {
					session.setAttribute("isLoginIndex",false);
					response.sendRedirect(request.getContextPath()+"/plan/ui.do");
				}
			}
			if(user.getHobby()!=null && user.getHobby().contains(Constant.P_POLICY)) {
				if(isLoginIndex) {
					session.setAttribute("isLoginIndex",false);
					response.sendRedirect(request.getContextPath()+"/policy/ui.do");
				}
			}
//			if(user.getHobby()!=null && user.getHobby().contains(Constant.P_YWY)) {
//				if(isLoginIndex) {
//					session.setAttribute("isLoginIndex",false);
//					response.sendRedirect(request.getContextPath()+"/plans/download_plansUI.do");
//				}
//			}
			if(user.getHobby()!=null && user.getHobby().contains(Constant.P_BID)) {
				if(isLoginIndex) {
					session.setAttribute("isLoginIndex",false);
					response.sendRedirect(request.getContextPath()+"/bid/ui.do");
				}
			}
			return true;
		}
		/***
		 * 用户没登录，先登录
		 */
		if(header == null) {//传统同步请求
			response.sendRedirect(request.getContextPath()+"/login.jsp");
		} else {//ajax异步请求
			writeSecurityFilter(request,response,Constant.LOGIN_CODE);
		}
		return false;
	}
	
	private void writeSecurityFilter(HttpServletRequest request, HttpServletResponse response,int code) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonResult jsonResult = JsonResult.failure(""+code, "您没有权限！！！");
            /***
             * 把jsonResult对象，转换成json格式的字符串，并写入到response对象里
             */
            String jsonString = mapper.writeValueAsString(jsonResult);
            writer = response.getWriter();
            writer.print(jsonString);
            return;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }
	
	public static void main(String[] args) {
		ResourceBundle rb = ResourceBundle.getBundle("excludeUrl");
		Enumeration<String> keys = rb.getKeys();
		while(keys.hasMoreElements()) {
			System.out.println(keys.nextElement());
		}
	}
	
}
